import {getRequest} from "@/utils/api";

export const initMenu = (router,store) => {
    // 判断store中router是否有值,有值直接返回,避免不必要的操作
    if (store.state.router.length > 0) {
        return;
    }

    getRequest('/system/config/menu').then(data => {
        if (data) {
            // 格式化菜单数据
            let fmtRoutes = formatRoutes(data);
            // 添加到router中
            router.addRoutes(fmtRoutes);
            // 将数据存入vuex
            store.commit('initRoutes',fmtRoutes);
            store.dispatch('connect')
        }
    })

}


export const formatRoutes = (routes) => {
    let fmtRoutes = [];
    routes.forEach(router => {
        let {
            path,
            component,
            name,
            iconCls,
            children
        } = router;
        if (children && children instanceof Array) {
            //递归
            children = formatRoutes(children);
        }
        let fmtRouter = {
            path:path,
            name:name,
            iconCls:iconCls,
            children:children,
            component(resolve) {
                // 为了让点击其他页面可以显示。因为Emp、Per等页面的显示是在Home基础上
                if (component.startsWith('Home')) {
                    require(['../views/' + component + '.vue'],resolve);
                }else if (component.startsWith('Emp')) {
                    require(['../views/emp/' + component + '.vue'],resolve);
                }else if(component.startsWith('Per')) {
                    require(['../views/per/' + component + '.vue'],resolve);
                }else if(component.startsWith('Sal')) {
                    require(['../views/sal/' + component + '.vue'],resolve);
                }else if(component.startsWith('Sta')) {
                    require(['../views/sta/' + component + '.vue'],resolve);
                }else if(component.startsWith('Sys')) {
                    require(['../views/sys/' + component + '.vue'],resolve);
                }
            }
        }
        fmtRoutes.push(fmtRouter);
    });
    return fmtRoutes;

}